package org.argus.common.web.core.data;

import lombok.extern.slf4j.Slf4j;
import org.argus.common.core.annotation.ValueField;
import org.argus.common.core.utils.ReflectUtils;

import java.lang.reflect.Field;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/7/28
 */
@Slf4j
public class DataValueCacheUtils {

    private static final String DATA_CACHE_KEY_PREFIX = "dc:";

    /**
     * 生成数据缓存key
     * @param sourceTable
     * @param keyColumn
     * @param keyValue
     * @param valueColumn
     * @return
     */
    public static String buildDataCacheKey(String sourceTable, String keyColumn, String keyValue, String valueColumn) {
        return DATA_CACHE_KEY_PREFIX + sourceTable + ":" + keyColumn + ":" + keyValue + ":" + valueColumn;
    }

    /**
     * 获取自定字段的 annotation.keyValueSourceField 指定的值.
     * @param target
     * @param annotation
     * @return
     */
    public static String getKeyValue(Object target, ValueField annotation) {
        String byFieldName = annotation.by();
        try {
            Field byField = ReflectUtils.getField(target.getClass(), byFieldName);
            if (byField == null) {
                String msg = "The key field " + byFieldName + " cannot be found.";
                log.error(msg);
                throw new IllegalArgumentException(msg);
            }
            byField.setAccessible(true);
            Object keyValue = byField.get(target);
            if (keyValue == null) {
                log.info("The key field {} is null.", byFieldName);
                return null;
            }
            return keyValue.toString();
        } catch (IllegalAccessException e) {
            log.error("The key field " + byFieldName + " cannot be accessed.", e);
            throw new IllegalArgumentException(e);
        }
    }
}
